#!/usr/bin/env bash

# kibana配置文件
function kibana_config() {
  local esHost="127.0.0.1:9200"

  echo_red "本机和docker容器IP地址如下(如有多网卡ip可能会不准确,请自行确认)"
  hostname -I | awk '{print $1}'
  docker inspect -f '{{.Name}} - {{.NetworkSettings.IPAddress }}' $(docker ps -q)

  esHost=$(read_input "请输入elasticsearch的地址和端口号：" ${esHost})

  echo_sleep "\n开始写入配置文件……"
  echo server.name: kibana >>${applicationPath}/config/kibana.yml
  echo server.host: "0.0.0.0" >>${applicationPath}/config/kibana.yml
  echo elasticsearch.hosts: ["http://${esHost}"] >>${applicationPath}/config/kibana.yml
  echo xpack.monitoring.ui.container.elasticsearch.enabled: true >>${applicationPath}/config/kibana.yml
  echo i18n.locale: "zh-CN" >>${applicationPath}/config/kibana.yml
  echo_sleep "配置文件写入完成！\n"
}

# 判断容器是否启动成功
function kibana_successOrNot() {
  echo_sleep "docker run命令:\n $dockerRunCmd \n" 2
  if [[ -n $(docker ps -q -f "name=^$application$") ]]; then
    echo -e "$application 容器启动成功"
    echo -e "\t端口号：$port"
    echo -e "\t版本号：$version"
    echo -e "\t容器名称：$application"
    echo -e "\t本地映射路径：$applicationPath"
    echo -e "进入容器使用命令：docker exec -it $application /bin/bash"
    echo -e "web页面访问地址: http://host:${port}"
  else
    log_error "$application 容器启动失败,请检查docker run命令是否有误,端口是否被占用"
  fi
}

# 安装kibana
function kibana_install() {
  application="kibana"                         # 应用名称,docker ps中显示的名称
  image="kibana"                               # docker仓库中镜像名称
  applicationPath="/opt/kibana/${application}" # 本地映射文件路径
  port="5601"                                  # 对外映射的端口号
  version="7.17.10"                            # 镜像版本号,默认为7.17.10 8.0以上安装报错

  echo -e "\n=========================开始安装Kibana========================="

  echo_yellow "1.检测是否存在 ${application} 容器"
  docker_delExisting ${application}

  echo_yellow "2.开始拉取镜像文件"
  echo_red "\n版本号要与ElasticSearch的版本一致"
  docker_pull

  echo_yellow "3.开始创建本地映射目录"
  create_file_path config

  echo_yellow "4.开始创建配置文件"
  elasticSearch_config

  echo_yellow "5.创建并启动docker容器"
  port=$(read_input "请输入需要映射的端口(默认为 ${port})：" ${port})
  application=$(read_input "请输入容器的名称(默认为 ${application})：" ${application})

  echo -e "${application}启动中,请等待......"

  dockerRunCmd="docker run  --restart=always  --privileged=true \
	--name ${application} \
	-p $port:5601 \
	-v $applicationPath/config/kibana.yml:/usr/share/kibana/config/kibana.yml \
	-v /etc/localtime:/etc/localtime:ro \
	-d $image:$version &> /dev/null"

  eval $dockerRunCmd

  echo_yellow "6.检测容器是否启动成功"
  kibana_successOrNot

  echo -e "=========================安装Kibana结束========================="
}
